package Waya::Variation; 

use warnings;
use strict;
use Waya::Constants ':traverse';

use base 'Waya::Base';

sub mainline   { $_[0]->[0]     }
sub variation  { $_[0]->[$_[1]] }
sub variations { @{$_[0]}       }

sub as_sgf {
    my $self = shift;
    no warnings 'recursion';
    join '' => 
        map { sprintf "\n(%s)" => $_->[0]->as_sgf }
        $self->variations;
}


sub traverse_node {
    my ($self, $code) = @_;

    # pruning doesn't matter here - if the code wants to prune a node, all the
    # other variations are still being processed.

    no warnings 'recursion';
    # $_->[0]->traverse_node($code) for $self->variations;

    # can't splice during the for loop, so we collect the remaining variations
    # in an another array, which we overlay onto $self.

    my @new_variations;

    for my $variation ($self->variations) {
        my $rc = $variation->[0]->traverse_node($code);
        push @new_variations => $variation unless $rc == RC_DELETE;
    }

    @$self = @new_variations;

    return RC_CONTINUE;
}


sub traverse_coord {
    my ($self, $code) = @_;

    # pruning doesn't matter here - if the code wants to prune a node, all the
    # other variations are still being processed.

    no warnings 'recursion';

    $_->[0]->traverse_coord($code) for $self->variations;
    return RC_CONTINUE;
}


# This is - as I shouldn't need to tell you - a dirty hack.
# But I like it.
sub DESTROY {}
sub AUTOLOAD {
    our $AUTOLOAD=~ s/Variation/Node/;
    &$AUTOLOAD($_[0]->mainline, @_[1..@_]);
}


1;
